const XLSX = require('../../utils/xlsx.core.min.js');

// 添加生成随机柔和颜色的函数
function getPastelColor() {
  // 使用较高的基础值来确保颜色偏淡
  const baseColor = 255; // 基础色值，确保颜色足够淡
  const variation = 66;  // 色值变化范围，避免颜色太深
  
  const r = baseColor - Math.floor(Math.random() * variation);
  const g = baseColor - Math.floor(Math.random() * variation);
  const b = baseColor - Math.floor(Math.random() * variation);
  
  return `rgb(${r}, ${g}, ${b})`;
}

Page({
  data: {
    weekDays: [
      { week: '周一' },
      { week: '周二' },
      { week: '周三' },
      { week: '周四' },
      { week: '周五' },
    ],
    timeSlots: [
      { section: 1, time: '09:00-10:20' },
      { section: 2, time: '10:40-12:00' },
      { section: 3, time: '12:30-13:50' },
      { section: 4, time: '14:00-15:20' },
      { section: 5, time: '15:30-16:50' },
      { section: 6, time: '17:00-18:20' },
      { section: 7, time: '19:00-20:20' },
      { section: 8, time: '20:30-21:50' }
    ],
    courses: [
      {
        name: '微信小程序进阶与实战',
        code: 'KN',
        teacher: '张三',
        room: 'U110',
        day: 0,
        section: 1,
        weeks: '1 2 3 4 5 6 7 8 '
      },
      {
        name: '微信小程序应用开发',
        code: 'GG',
        teacher: '李四',
        room: 'U110',
        day: 1,
        section: 1,
        weeks: '1 2 3 4 5 6 7 8 '
      }
    ],
    courseGrid: [], // 二维数组存储课程信息
    debugText: '' // 用于调试显示
  },

  processCoursesData() {
    const grid = Array(8).fill(null).map(() => Array(5).fill(null));
    
    this.data.courses.forEach(course => {
      if (course.section >= 1 && course.section <= 8 && course.day >= 0 && course.day <= 4) {
        // 如果课程没有背景色，添加一个
        if (!course.bgColor) {
          course.bgColor = getPastelColor();
        }
        grid[course.section - 1][course.day] = course;
      }
    });
    
    this.setData({
      courseGrid: grid,
      debugText: JSON.stringify(this.data.courses)
    });
  },

  onLoad() {
    console.log('页面加载开始');
    const courses = wx.getStorageSync('courses');
    
    if (courses && courses.length > 0) {
      // 为已有的课程添加随机背景色
      courses.forEach(course => {
        if (!course.bgColor) {
          course.bgColor = getPastelColor();
        }
      });
      
      this.setData({ courses }, () => {
        this.processCoursesData();
      });
    } else {
      this.processCoursesData();
    }
  },

  importSchedule() {
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      extension: ['xlsx', 'xls'],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].path;
        
        wx.getFileSystemManager().readFile({
          filePath: tempFilePath,
          encoding: 'binary',
          success: (res) => {
            try {
              const workbook = XLSX.read(res.data, { type: 'binary' });
              const firstSheetName = workbook.SheetNames[0];
              const worksheet = workbook.Sheets[firstSheetName];
              const jsonData = XLSX.utils.sheet_to_json(worksheet);
              
              const weekMap = {
                '周一': 0,
                '周二': 1,
                '周三': 2,
                '周四': 3,
                '周五': 4
              };
              
              const courses = jsonData.map(item => {
                const weekMap = {
                  '周一': 0,
                  '周二': 1,
                  '周三': 2,
                  '周四': 3,
                  '周五': 4
                };
                const section = Number(item['节次']);
                const day = weekMap[item['星期']];
                const weeks = item['周数'].split(' ').map(week => Number(week));
                
                if (isNaN(section) || day === undefined) {
                  return null;
                }
                
                return {
                  name: (item['课程名称'] || '').trim(),
                  code: (item['课程代码'] || '').trim(),
                  teacher: (item['教师'] || '').trim(),
                  room: (item['教室'] || '').trim(),
                  day: day,
                  section: section,
                  weeks: weeks,
                  bgColor: getPastelColor()
                };
              }).filter(course => course !== null);
              
              if (courses.length > 0) {
                this.setData({ courses }, () => {
                  this.processCoursesData();
                });
                
                wx.setStorageSync('courses', courses);
                
                wx.showToast({
                  title: '导入成功',
                  icon: 'success'
                });
              } else {
                wx.showToast({
                  title: '未找到有效数据',
                  icon: 'error'
                });
              }
            } catch (error) {
              console.error('Excel解析失败:', error);
              wx.showToast({
                title: '文件解析失败',
                icon: 'error'
              });
            }
          },
          fail: (err) => {
            console.error('文件读取失败:', err);
            wx.showToast({
              title: '文件读取失败',
              icon: 'error'
            });
          }
        });
      }
    });
  },

  showCourseWeeks(event) {
    const course = event.currentTarget.dataset.course;
    if (course && course.weeks) {
      const weeksString = course.weeks;
      wx.showToast({
        title: `上课周数: ${weeksString}`,
        icon: 'none',
        duration: 2000
      });
    }
  }
});